package com.echo.util;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;

public class StringUtil {

	/**
	 * <P>判断是否为NULL或空字符换</P>
	 * @param arg
	 * @return
	 */
	public static boolean isNullEmpty(String arg) {
		if(arg == null) {
			return true;
		}
		if(arg.trim().equals("")) {
			return true;
		}
		return false;
	}
	
	/**
	 * <P>判断俩字符串是否相等</P>
	 * @param first
	 * @param second
	 * @return
	 */
	public static boolean isEquals(String first,String second) {
		if (first.trim().equals(second.trim())) {
			return true;
		}
		return false;
	}
	
	/**
	 * <P>集合返回字符串，以逗号分隔</P>
	 * @param list
	 * @return
	 */
	public static String getStringFromList(List<String> list) {
		if (null == list || list.size() <= 0) {
			return "";
		}
		
		StringBuffer buffer = new StringBuffer();
		for (String str : list) {
			buffer.append(str + ",");
		}
		
		String str = buffer.toString();
		return str.substring(0, str.length() - 1);
	}
	/**
	 * 采用正则表达 过滤SQL需要替换占位符
	 * @param source
	 */
	public static String[]  sqlPatternRender(String source){
		String newSql=source;
		StringBuffer sb =new StringBuffer("");
		Pattern p = Pattern.compile("(#\\{[^\\}]*\\})");  
		Matcher m = p.matcher(source);  
		while(m.find()){  
			String temp=m.group(1);
			sb.append(temp.replaceAll("\\}", "").replaceAll("#\\{", "")).append(";");
			newSql=newSql.replaceFirst(escapeExprSpecialWord(temp), "?");
			}
	     if(sb.length()>=1)
	return new String[]{newSql,sb.toString()};
	     else
		return  null;
	}
	/**
	 * 转义正则特殊字符 （$()*+.[]?\^{},|）
	 * 
	 * @param keyword
	 * @return 转义后字符串
	 */
	public static String escapeExprSpecialWord(String keyword) {
		if (StringUtils.isNotBlank(keyword)) {
			String[] fbsArr = { "\\", "$", "(", ")", "*", "+", ".", "[", "]", "?", "^", "{", "}", "|" };
			for (String key : fbsArr) {
				if (keyword.contains(key)) {
					keyword = keyword.replace(key, "\\" + key);
				}
			}
		}
		return keyword;
	}
	  /**
	   * 捕获异常信息并返回字符串
	   * @param e
	   */
	  public  static String getMysqlExceptionMes(Exception e){
	  	  //获取异常信息
	      ByteArrayOutputStream stream = new ByteArrayOutputStream();
	      e.printStackTrace(new PrintStream(stream));
	      return   stream.toString();
	 
	  }
	  
	  /**
	   * 数字型1是/2否转布尔型
	   * @param o
	   */
	  public static boolean toBooleanFromNum(Object o){
	  	  //转换		  
		  if(o==null)return false;
		  if(o.equals("1")){
			return true;
		  }else{
			return false;
		  }	 
	  }
	  
	/**
	 * 数字型1是/2否转布尔型
	 * 
	 * @param o
	 */
	public static String getUpdateSqlSelective(String[] param, Map sqlKey, Map map,
			String tableName, String cndKeyName) {
		StringBuilder strb = new StringBuilder(128);
		int t = 0;
		strb.append("UPDATE ").append(tableName).append(" SET ");
		for (String string : param) {
			if (map.containsKey(string)) {
				if (++t == 1) {// 第一个key前部无需加逗号
					strb.append(sqlKey.get(string)).append("=");
					strb.append("#{").append(string).append("}");
				} else {
					strb.append(", ").append(sqlKey.get(string)).append("=");
					strb.append("#{").append(string).append("}");
				}
			}
		}
		//根据更新条件键加入条件
		if(map.containsKey(cndKeyName)){
			strb.append(" WHERE ").append(sqlKey.get(cndKeyName)).append("=");
			strb.append("#{").append(cndKeyName).append("}");
		}else{
			strb.append(" WHERE 1=2");
		}
		return strb.toString();
	}
	
	/**
	 * 数字型1是/2否转布尔型
	 * 
	 * @param o
	 */
	public static String getInsertSqlSelective(String[] param, Map sqlKey, Map map,
			String tableName) {
		StringBuilder strb = new StringBuilder(128);
		int t = 0;
		strb.append("INSERT INTO ").append(tableName).append("(");
		//字段
		for (String string : param) {
			if (map.containsKey(string)) {
				if (++t == 1) {// 第一个key前部无需加逗号
					strb.append(sqlKey.get(string));
				} else {
					strb.append(", ").append(sqlKey.get(string));
				}
			}
		}
		strb.append(")values(");
		
		//值参
		t=0;
		for (String string : param) {
			if (map.containsKey(string)) {
				if (++t == 1) {// 第一个key前部无需加逗号					
					strb.append("#{").append(string).append("}");
				} else {					
					strb.append(", #{").append(string).append("}");
				}
			}
		}
		
		strb.append(")");		
		
		return strb.toString();
	}
	
	
	/**
	 * 增加时间格式验证
	 * @param email
	 * @return
	 */
	public static boolean validateDateFormat(String date){  
		 Pattern p = Pattern.compile("^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\\s(((0?[0-9])|([1-2][0-3]))\\:([0-5]?[0-9])((\\s)|(\\:([0-5]?[0-9])))))?$"); 
		   return p.matcher(date).matches(); 

	}
	
	/**
	 * 增加邮箱验证工具
	 * @param email
	 * @return
	 */
	public static boolean validateEmail(String email){  
        //Pattern pattern = Pattern.compile("[0-9a-zA-Z]*.[0-9a-zA-Z]*@[a-zA-Z]*.[a-zA-Z]*", Pattern.LITERAL);  
        if(email == null){  
            return false;  
        }  
        //验证开始  
        //不能有连续的.  
        if(email.indexOf("..") != -1){  
            return false;  
        }  
        //必须带有@  
        int atCharacter = email.indexOf("@");  
        if (atCharacter == -1) {  
            return false;  
        }  
        //最后一个.必须在@之后,且不能连续出现  
        if(atCharacter > email.lastIndexOf('.') || atCharacter+1 == email.lastIndexOf('.')){  
            return false;  
        }  
        //不能以.,@结束和开始  
        if (email.endsWith(".") || email.endsWith("@") || email.startsWith(".") || email.startsWith("@")) {  
            return false;  
        }  
        return true;  
    }  
	  
	  
	  public static void main(String[] str){
		  String[] userParam=new String[]{"nickName","password","email","sex","job","countryId","weight","height","signature","mobile","degree","imgUrl","isEnable","isNotice","isOpenArchives","isBind"};
		     Map<String,String> sqlKey=new HashMap<>();
		     					sqlKey.put("nickName", "memb_nickname");
		     					sqlKey.put("password", "memb_password");
		     					sqlKey.put("email", "memb_email");
		     					sqlKey.put("sex", "memb_sex");
		     					sqlKey.put("job", "memb_job");
		     					sqlKey.put("countryId", "memb_countryid");
		     					sqlKey.put("weight", "memb_weight");
		     					sqlKey.put("height", "memb_height");
		     					sqlKey.put("signature", "memb_signature");
		     					sqlKey.put("mobile", "memb_mobile");
		     					sqlKey.put("degree", "memb_degree");
		     					sqlKey.put("imgUrl", "memb_imgurl");
		     					sqlKey.put("isEnable", "memb_isenable");
		     					sqlKey.put("isNotice", "memb_isnotice");
		     					sqlKey.put("isOpenArchives", "memb_isopenarchives");
		     					sqlKey.put("isBind", "memb_isbind");
		     					sqlKey.put("birthday", "memb_birthday");
		     					
		     					sqlKey.put("gagaId", "memb_gagaid");
		     		
		     					Map<String,String> map=new HashMap<>();
		     					//map.put("gagaId", "11111");//主键
		     					map.put("nickName", "海浪");
		     					
	   System.out.println(getUpdateSqlSelective(userParam, sqlKey, map, "t_member", "gagaId"));
	  }
	  
}
